import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import joblib

# 准备数据
# 特征：第一门考试成绩、第二门考试成绩
X = np.array([[90, 85],
              [85, 80],
              [30, 40],
              [40, 50],
              [60, 70]])

# 标签：是否被录取（1表示录取，0表示未录取）
y = np.array([1, 1, 0, 0, 1])

# 数据分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 模型选择
model = LogisticRegression()

# 模型训练
model.fit(X_train, y_train)

# 模型评估
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"准确率: {accuracy}")

# 绘制决策边界
# 生成网格点
x1_min, x1_max = X[:, 0].min() - 5, X[:, 0].max() + 5
x2_min, x2_max = X[:, 1].min() - 5, X[:, 1].max() + 5
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max, 0.1))
# 对网格点进行预测
Z = model.predict(np.c_[xx1.ravel(), xx2.ravel()])
Z = Z.reshape(xx1.shape)
# 绘制等高线
plt.contourf(xx1, xx2, Z, alpha=0.4)
# 绘制训练集样本点
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, marker='o', edgecolor='black', label='Training data')
# 绘制测试集样本点
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, marker='x', edgecolor='black', label='Testing data')
plt.xlabel('Exam 1 Score')
plt.ylabel('Exam 2 Score')
plt.title('Logistic Regression')
plt.legend()
plt.show()

# 保存模型
joblib_file = "logistic_regression_model.pkl"
joblib.dump(model, joblib_file)
print(f"模型已保存到 {joblib_file}")

# 加载模型
loaded_model = joblib.load(joblib_file)

# 进行预测
new_data = np.array([[99, 100], [60, 60], [80, 80], [20, 70]])
prediction = loaded_model.predict(new_data)
print(f"预测值: {prediction}")
